﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using System.Text;

namespace Win7RovMobileApp
{
    public partial class ConfirmationScreen : PhoneApplicationPage
    {
        private RovinieteServiceReference.Windows_Phone_7_ServiceClient client;
        private SavedOptions so;

        // color animation on OrderButton
        private DispatcherTimer ColorAnimationTimer;         
        private int ColorAnimationCounter;
        private String encodeDecodeKey = "alba-ca-zapada-si-cei-sapte-pitici";
        private enum enEnCryptDecrypt
        {
            DECRYPT, ENCRYPT
        }; 

      
        public ConfirmationScreen()
        {
            InitializeComponent();
            DataContext = so = App.UserPreferences;
            client = new RovinieteServiceReference.Windows_Phone_7_ServiceClient();

            ColorAnimationTimer = new DispatcherTimer();
            ColorAnimationTimer.Interval = new TimeSpan(0, 0, 0, 0, 150);
            ColorAnimationTimer.Tick += new EventHandler(RunColorAnimation);   
            ColorAnimationTimer.Start();
        }


        private void RunColorAnimation(object obj, EventArgs e)
        {
            int chosenColor = ColorAnimationCounter % 3;
            switch(chosenColor)
            {
                case 0:
                    {
                        OrderButton.Foreground = new SolidColorBrush(Colors.Blue);        
                        break;
                    }
                case 1:
                    {
                        OrderButton.Foreground = GetColorFromHexa("#FF004EFF");
                        break;
                    }
                case 2:
                    {
                        OrderButton.Foreground = GetColorFromHexa("#FF0076FF");
                        break;
                    }
            }

            ColorAnimationCounter++;            
        }


        private SolidColorBrush GetColorFromHexa(string hexaColor)
        {
            return new SolidColorBrush(
                Color.FromArgb(
                    Convert.ToByte(hexaColor.Substring(1, 2), 16),
                    Convert.ToByte(hexaColor.Substring(3, 2), 16),
                    Convert.ToByte(hexaColor.Substring(5, 2), 16),
                    Convert.ToByte(hexaColor.Substring(7, 2), 16)
                )
            );
        }


        private void PlaceOrder_Click(object sender, RoutedEventArgs e)
        {
            client.CheckAvailabilityDuplicatesCompleted += new EventHandler<RovinieteServiceReference.CheckAvailabilityDuplicatesCompletedEventArgs>(client_CheckAvailabilityDuplicatesCompleted);
            client.InsertRecordCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_InsertRecordCompleted);

            client.CheckAvailabilityDuplicatesAsync(so.ValabilityStartDate, so.VehiclePlate);
        }


        void client_CheckAvailabilityDuplicatesCompleted(object sender, RovinieteServiceReference.CheckAvailabilityDuplicatesCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.Result == false)
                {
                    MessageBox.Show("Exista deja o rovinieta VALIDA pentru acest numar de inmatriculare! Comanda nu e necesara!");
                    return;
                }

                String encryptedCardNumber          = EncryptDecryptInfo(so.CardNumber, encodeDecodeKey, enEnCryptDecrypt.ENCRYPT);
                String encryptedCardOwner           = EncryptDecryptInfo(so.CardOwner, encodeDecodeKey, enEnCryptDecrypt.ENCRYPT);
                String encryptedCardSecurityNumber  = EncryptDecryptInfo(so.CardSecurityNumber, encodeDecodeKey, enEnCryptDecrypt.ENCRYPT);
                String valabilityCode               = App.UserPreferences.Valabilities[App.UserPreferences.Valability];
                
                client.InsertRecordAsync(so.VehiclePlate, so.VehicleCountry, so.VehicleCategories[so.VehicleType], valabilityCode, so.ValabilityStartDate, so.OwnerName,
                    so.OwnerAlias, so.SocialSecurityNumber, so.Adress, so.PhoneNumber, so.Email, so.ClientCity, so.ClientProvince, so.CardType, encryptedCardOwner, encryptedCardNumber, encryptedCardSecurityNumber, so.TotalCosts, (so.ClientType == "Fizica") ? false : true, so.VehicleCountry);
            }
        }

        void client_InsertRecordCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MessageBox.Show("Comanda a fost trimisa cu succes!\nVa multumim!");

                //reset all fields for next user preferences
                App.UserPreferences = new SavedOptions();

                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
            else
            {
                MessageBox.Show("Comanda nu a fost inregistrata cu succes. Va rugam mai incercati o data.");
            }
        }


        private string EncryptDecryptInfo(String Message, String Key, enEnCryptDecrypt EnC)
        {
            int messageCount, keyCount, value = 0;             
            StringBuilder strRetVal = new StringBuilder();
          
            for (messageCount = 0, keyCount = 0; messageCount < Message.Length; messageCount++, keyCount++)
            {
                if (keyCount >= Key.Length)
                {
                    keyCount = 0;
                }
                
                // Rotates the Key string counter to Zero when character value 
                // is traversed till end
                if (EnC == enEnCryptDecrypt.ENCRYPT)
                {
                    //When Encryption is required we add ASCII value of key with Message
                    value = (Message[messageCount]) + (Key[keyCount]);
                }
                else
                {
                    //When Decryption is required we subtract ASCII value of key with Message
                    value = (Message[messageCount]) - (Key[keyCount]);
                }

                // Here we convert the ASCII value to character and Append that to Stringbuilder
                strRetVal.Append((char)(value));                 
            }

            //Returns the Processed String.
            return strRetVal.ToString(); 
        }


    }
}   